<template>
    <view style="display: flex; flex-direction: column">
        <view class="search_menu">
            <view
                @click="changeEvent(index)"
                :class="index == type ? 'search_menu_item_sel' : 'search_menu_item'"
                v-for="(item, index) in menu"
                :key="index"
                >{{ item }}</view
            >
        </view>
        <view v-if="type == 0">
            <view style="margin-left: 30rpx; font-size: 28rpx; color: #999999; line-height: 40rpx; margin-top: 30rpx">
                *当前支持以下智能秤</view
            >
            <view class="device_cell">
                <image
                    style="width: 160rpx; height: 160rpx; border-radius: 16rpx; margin-left: 30rpx"
                    src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/balance.png"
                ></image>
                <label style="margin-left: 20rpx; color: #333333; font-size: 32rpx">倾小体</label>
                <view @click="goToBindDevice" class="device_active_btn device_active_btn_green">绑定</view>
            </view>
            <view v-if="deviceList.length > 0" class="device_list">
                <label style="font-weight: 500; margin-left: 30rpx; margin-top: 30rpx; color: #333333; font-size: 28rpx"
                    >我的设备</label
                >
                <view class="device_cell" v-for="(item, index) in deviceList" :key="index">
                    <image
                        style="width: 160rpx; height: 160rpx; border-radius: 16rpx; margin-left: 30rpx"
                        src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/balance.png"
                    ></image>
                    <view style="margin-left: 20rpx; display: flex; flex-direction: column">
                        <label style="color: #333333; font-size: 32rpx">{{ item.name }}</label>
                        <label style="margin-top: 8rpx; color: #999999; font-size: 28rpx">已保存</label>
                        <image src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/unlink.png" class="unlink" @click="onUnlink(item.id)"/>
                    </view>
                    <view
                        @click="connectBlue(item)"
                        :class="connectDeviceId == item.deviceId ? 'device_normal_btn' : 'device_active_btn'"
                    >
                        {{ connectDeviceId == item.deviceId ? "已连接" : "连接" }}
                    </view>
                </view>
            </view>
        </view>
        <view v-if="type == 1">
            <view class="tip_head">
                <image
                    style="margin-left: 30rpx; height: 28rpx; width: 28rpx"
                    src="https://smosun-minapp.oss-cn-shanghai.aliyuncs.com/weapp/img/wo/tip_icon.png"
                ></image>
                <label style="margin-left: 12rpx; color: #ff822e; font-size: 28rpx"
                    >请打开蓝牙、打开wifi｜手机靠近体脂秤</label
                >
            </view>
            <view class="wifi_menu">
                <view class="wifi_cell1">
                    <label class="cell_title">wifi名称</label>
                    <view style="margin-left: auto; margin-right: 0rpx; display: flex; flex-direction: row-reverse">
                        <view @click="showWifiList()" style="color: #418170; font-size: 28rpx">切换网络</view>
                        <input
                            v-model="wifiName"
                            placeholder="wifi名称"
                            disabled
                            style="
                                width: 300rpx;
                                margin-right: 30rpx;
                                color: #333333;
                                font-size: 28rpx;
                                text-align: right;
                            "
                        />
                    </view>
                </view>
                <view class="wifi_cell2">
                    <label class="cell_title">wifi密码</label>
                    <view style="margin-left: auto; margin-right: 0rpx; display: flex; flex-direction: row-reverse">
                        <input
                            v-model="wifiPassword"
                            placeholder="输入wifi密码"
                            style="
                                width: 300rpx;
                                margin-right: 0rpx;
                                color: #333333;
                                font-size: 28rpx;
                                text-align: right;
                            "
                        />
                    </view>
                </view>
            </view>
            <bottom-big-btn-view btnTitle="连接" @commit="peiWang"></bottom-big-btn-view>
        </view>
        <wifi-list-view
            :selWifi="wifiName"
            :show="showWifi"
            :list="wifiList"
            @close="showWifi = false"
            @selectWifi="selectWifiEvent"
        ></wifi-list-view>
    </view>
</template>

<script>
import common from "@/common/common.js";
import { mapState } from "vuex";
import utils from "@/utils/utils";
export default {
    data() {
        return {
            type: 0,
            menu: ["蓝牙连接", "wifi连接"],
            deviceList: [],
            wifiName: "",
            wifiPassword: "",
            wifiList: [],
            showWifi: false,
            isUploading: false,
            weightUploading: 0,
            resistanceUploading: 0,
            uploadSuccess: false,
        };
    },
    computed: {
        ...mapState(["connectDeviceId", "isOpenBle", "devicesList"]),
    },
    watch: {
        connectDeviceId(value) {
            if (value) {
                this.notifyBLECharacteristicValueChange(value);
            }
        },
    },
    onShow() {
        this.requestDeviceList();
    },
    onLoad() {
        uni.startWifi({
            success: () => {
                uni.getConnectedWifi({
                    success: (res) => {
                        if (res.errMsg == "getConnectedWifi:ok") {
                            this.wifiName = res.wifi.SSID;
                            const wifiInfo = JSON.parse(uni.getStorageSync("wifiInfo") || "{}");
                            console.log("初始化wifi时", wifiInfo);
                            this.wifiPassword = wifiInfo[this.wifiName] || "";
                        }
                    },
                    fail: (err) => {},
                });
            },
        });
    },
    onUnload() {
        this.uploadSuccess = false;
    },
    methods: {
        checkBluetoothStatus() {
            return new Promise((resolve, reject) => {
                uni.openBluetoothAdapter({
                    success(res) {
                        resolve(true);
                    },
                    fail(err) {
                        resolve(false);
                    },
                });
            });
        },
        changeEvent(index) {
            if (this.uploadSuccess && index === 0) {
                uni.navigateBack();
            }
            this.type = index;
        },
        requestDeviceList() {
            uni.showLoading();
            this.request.httpTokenJsonRequest("/mp-api/wx/device/list", null, "POST", true).then((res) => {
                uni.hideLoading();
                if (res.code == 0) {
                    this.deviceList = res.data.list;
                }
            });
        },
        async goToBindDevice() {
            const status = await this.checkBluetoothStatus();
            if (!status) {
                common.showToast("蓝牙连接失败，请检查蓝牙后使用");
                return;
            }
            if (!this.isOpenBle) {
                await this.$store.dispatch("openBluetoothAdapter");
                await this.$store.dispatch("startBluetoothDevicesDiscovery");
            }
            uni.navigateTo({
                url: "/pages/bindDevice/bindDevice",
            });
        },

        async connectBlue(item) {
            console.log("连接蓝牙页 item", item);
            const status = await this.checkBluetoothStatus();
            if (!status) {
                common.showToast("蓝牙连接失败，请检查蓝牙后使用");
                return;
            }
            console.log("连接蓝牙页 isOpenBle", this.isOpenBle);
            if (!this.isOpenBle || this.devicesList.length === 0) {
                await this.$store.dispatch("openBluetoothAdapter");
                await this.$store.dispatch("startBluetoothDevicesDiscovery");
            }
            console.log("连接蓝牙页 devicesList", this.devicesList);
            console.log(this.devicesLis, item, "pooooo=--0-000001");
            // if (this.devicesList.some((device) => device.deviceId === item.deviceId)) {
            //     common.showToast("请确认体脂秤蓝牙是否开启");
            //     return;
            // }
            console.log("连接蓝牙页 connectDeviceId", this.connectDeviceId);
            // if (!this.connectDeviceId) {
            //     common.showToast("请确认体脂秤蓝牙是否开启");
            //     return;
            // }
            if (this.connectDeviceId == item.deviceId) {
                return;
            }
            uni.showLoading({
                title: "连接中...",
                mask: true,
            });
            try {
                this.$store
                    .dispatch("createBLEConnection", item)
                    .then(async (res) => {
                        // console.log(res, "popoooo-000连接出问题了");
                        uni.hideLoading();
                        try {
                            uni.onBLEConnectionStateChange((res) => {
                                console.log(
                                    "APP 监听蓝牙连接状态的改变结束回调 res,currentDevice",
                                    res,
                                    this.currentDevice,
                                );
                                if (res.deviceId == this.currentDevice.deviceId) {
                                    this.currentDevice.isconnect = res.connected;
                                    if (res.connected == false) {
                                        this.$store.commit("setConnectDeviceId", "");
                                        this.$store.commit("setConnectDeviceInfo", {});
                                        this.$store.commit("setDevicesList", []);
                                    }
                                }
                            });
                        } catch (e) {
                            console.warn("APP 监听蓝牙连接状态的改变 err", e);
                        }
                    })
                    .catch((err) => {
                        uni.hideLoading();
                        common.showToast("请确认体脂秤蓝牙是否开启");
                    });
            } catch (err) {
                uni.hideLoading();
            }
        },
        // 监听重量
        async notifyBLECharacteristicValueChange(deviceId) {
            const { serviceId, characteristicId } = require("@/common/sxsBalance.js");
            this.weightUploading = 0;
            this.resistanceUploading = 0;
            try {
                await this.$store.dispatch("checkDeviceService", {
                    deviceId,
                    serviceId,
                    characteristicId,
                });
                // 启用notify，必须先启用notify才能调用onBLECharacteristicValueChange
                await this.$store.dispatch("openNotify", {
                    deviceId: deviceId,
                    serviceId: serviceId,
                    characteristicId: characteristicId,
                });
                uni.onBLECharacteristicValueChange((res) => {
                    this.getWeight(res.value);
                });
            } catch (err) {
                // common.showToast('监听重量异常');
            }
        },
        getWeight(cpcl) {
            let characteristicValue = utils.ab2hex(cpcl);
            var trimedStr = characteristicValue.trim();
            var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
            var len = rawStr.length;
            if (len % 2 !== 0) {
                return "Illegal Format ASCII Code!";
            }
            var balanceType;
            var dataType;
            var againType;
            var resistance;
            var resistanceArr = [];
            var weight;
            var weightArr = [];
            for (var i = 0; i < len; i = i + 2) {
                if (i == 0) {
                    balanceType = rawStr.substr(i, 2);
                }
                if (i == 16) {
                    dataType = rawStr.substr(i, 2);
                }
                if (i == 18) {
                    againType = rawStr.substr(i, 2);
                }
                if (i == 6) {
                    weightArr.push(rawStr.substr(i, 2));
                }
                if (i == 8) {
                    weightArr.push(rawStr.substr(i, 2));
                }
                if (i == 10) {
                    resistanceArr.push(rawStr.substr(i, 2));
                }
                if (i == 12) {
                    resistanceArr.push(rawStr.substr(i, 2));
                }
                if (i == 14) {
                    resistanceArr.push(rawStr.substr(i, 2));
                }
            }
            weight = (parseInt(weightArr.reverse().join(""), 16) / 100).toFixed(2);
            resistance = parseInt(resistanceArr.reverse().join(""), 16);
            if (balanceType == "cf" && dataType == "00" && againType == "00") {
                this.uploadWeight(weight, resistance);
            }
        },
        uploadWeight(weight, resistance) {
            if (weight == this.weightUploading && this.resistanceUploading == resistance) {
                return;
            }
            var form = {
                resistance: resistance,
                weight: weight,
            };
            this.request.httpTokenJsonRequest("/mp-api/wx/weight/upload", form, "POST", true).then((res) => {
                this.isUploading = false;
                if (res.code == 0) {
                    this.weightUploading = weight;
                    this.resistanceUploading = resistance;
                    uni.$emit("uploadWeightSuccess", res.data);
                    this.uploadSuccess = true;
                    if (this.type === 0) {
                        uni.navigateBack();
                    }
                }
            });
        },

        // 选择wifi
        selectWifiEvent(e) {
            if (this.wifiName !== e) {
                this.wifiName = e;
                this.wifiPassword = "";
                const wifiInfo = JSON.parse(uni.getStorageSync("wifiInfo") || "{}");
                console.log("选择wifi时", wifiInfo);
                this.wifiPassword = wifiInfo[this.wifiName] || "";
            }
            this.showWifi = false;
        },
        // 配网
        async peiWang() {
            const status = await this.checkBluetoothStatus();
            if (!status) {
                common.showToast("蓝牙连接失败，请检查蓝牙后使用");
                return;
            }
            if (!this.isOpenBle) {
                await this.$store.dispatch("openBluetoothAdapter");
                await this.$store.dispatch("startBluetoothDevicesDiscovery");
            }
            if (this.wifiName == "") {
                uni.showToast({
                    title: "wifi名称不能为空",
                    icon: "none",
                });
                return;
            }
            uni.setStorageSync(
                "wifiInfo",
                JSON.stringify({
                    [this.wifiName]: this.wifiPassword,
                }),
            );
            uni.navigateTo({
                url: `/pages/blueConfigureNetwork/blueConfigureNetwork?ssid=${this.wifiName}&password=${this.wifiPassword}`,
            });
        },
        // 展示wifi列表
        showWifiList() {
            let that = this;
            uni.startWifi({
                success: function (res) {
                    uni.getWifiList({
                        success: function (res) {
                            uni.onGetWifiList(function (res) {
                                that.wifiList = utils.unique(res.wifiList, "SSID");
                                that.showWifi = true;
                            });
                        },
                    });
                },
                fail: function () {
                    uni.showToast({
                        icon: "none",
                        title: "获取wifi列表失败",
                    });
                },
            });
        },
        async onUnlink(id){
            const [,{confirm}]= await uni.showModal({ content: '确定解除绑定？' });
            if(confirm){
                await this.request.httpTokenJsonRequest("/mp-api/wx/device/bind", {
                    id,
                    type: 0
                }, "POST", true);
                this.requestDeviceList();
                uni.showToast({ title: '解绑成功', icon: 'none' });
            }
        }
    },
};
</script>

<style scoped>
.search_menu {
    height: 94rpx;
    width: 100%;
    display: flex;
    flex-direction: row;
}

.search_menu_item {
    height: 94rpx;
    width: 50%;
    line-height: 94rpx;
    font-size: 30rpx;
    text-align: center;
    font-weight: 500;
    color: #999999;
}

.search_menu_item_sel {
    height: 94rpx;
    width: 50%;
    line-height: 94rpx;
    font-size: 30rpx;
    text-align: center;
    font-weight: 500;
    color: #333333;
    position: relative;
}

.search_menu_item_sel::after {
    content: "";
    position: absolute;
    left: calc(50% - 16rpx);
    top: auto;
    bottom: 0;
    right: auto;
    height: 6rpx;
    width: 32rpx;
    background: linear-gradient(296deg, #36a782 0%, #56ccab 100%);
    box-shadow: 0px -4rpx 16rpx 0rpx rgba(57, 171, 134, 0.5);
}

.device_cell {
    height: 220rpx;
    border-radius: 24rpx;
    background-color: #fff;
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-top: 20rpx;
}

.device_active_btn {
    width: 114rpx;
    height: 48rpx;
    border-radius: 24rpx;
    border: 2rpx solid #FF822E;
    color: #FF822E;
    font-size: 24rpx;
    line-height: 48rpx;
    text-align: center;
    margin-left: auto;
    margin-right: 30rpx;
}
.device_active_btn_green{
    border: 2rpx solid #009977;
    color: #009977;
}
.device_normal_btn {
    width: 114rpx;
    height: 48rpx;
    border-radius: 24rpx;
    border: 2rpx solid #999999;
    color: #999999;
    font-size: 24rpx;
    line-height: 48rpx;
    text-align: center;
    margin-left: auto;
    margin-right: 30rpx;
}

.device_list {
    display: flex;
    flex-direction: column;
}

.tip_head {
    margin-top: 30rpx;
    height: 78rpx;
    width: 100%;
    background-color: #f6efea;
    display: flex;
    flex-direction: row;
    align-items: center;
}

.wifi_menu {
    margin-top: 30rpx;
    height: 220rpx;
    background-color: #fff;
    border-radius: 24rpx;
    display: flex;
    flex-direction: column;
}

.wifi_cell1 {
    height: 110rpx;
    margin-left: 30rpx;
    width: calc(100% - 60rpx);
    border-bottom: 2rpx #f6f6f6 solid;
    display: flex;
    flex-direction: row;
    align-items: center;
}

.wifi_cell2 {
    height: 110rpx;
    margin-left: 30rpx;
    width: calc(100% - 60rpx);
    display: flex;
    flex-direction: row;
    align-items: center;
}

.cell_title {
    color: #333333;
    font-size: 28rpx;
}
.unlink{
    width:65px;
    height:22px;
    margin-top: 5px;
}
</style>
